package edu.bbk.muc.lifetracker.sensormanager;

import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.util.Log;
import edu.bbk.muc.lifetracker.common.SensorsToUi;

/**
 * This class represents a general recorder for available sensors such as
 * acceleration, light,etc. and contains common methods and fields for these
 * sensors.
 * 
 * @author irenatyler and romankirillov
 * 
 */
public abstract class SensorRecorder extends Recorder {
  private boolean isActive = false; //indicates if this sensor recorder active
  private final SensorManager sensorService;
  protected AbstractSensorListener listener; //listener for this sensor recorder events
  protected Sensor sensor;
  protected int upadateInterval; //update interval for all types of SensorRecorder.

  /**
   * Initialises this and parent class fields.
   * @param currentActivity base application activity
   * @param callback Callback receiver for all sensor events
   */
  public SensorRecorder(Activity currentActivity, SensorsToUi callback) {
    super(currentActivity, callback);
    upadateInterval = 1000000; //set update interval to 1 second
    this.sensorService = (SensorManager) this.currentActivity.getSystemService(
            Activity.SENSOR_SERVICE);
  }

  @Override
  public void doStart() {
    if (isActive) {
      return;
    }

    Log.d(getTag(), "Sensor doStart()");

    getSensorManager().registerListener(
        getListener(),
        getSensor(),
        upadateInterval);
    isActive = true;
  }

  @Override
  public void doStop() {
    if (!isActive) {
      return;
    }

    Log.d(getTag(), "Sensor doStop()");

    getSensorManager().unregisterListener(getListener());
    isActive = false;
  }

  /**
   * Gets this sensor recorder listener.
   * @return this sensor recorder listener
   */
  protected abstract AbstractSensorListener getListener();

  /**
   * Gets this sensor recorder Sensor.
   * @return this sensor recorder Sensor
   */
  protected abstract Sensor getSensor();

  /**
   * Gets this Sensor recorder Sensor manager.
   * @return this Sensor recorder Sensor manager
   */
  protected SensorManager getSensorManager() {
    return sensorService;
  }

  /**
   * Gets Sensor type for specific sensor.
   * 
   * @return sensor type for specific sensor.
   */
  protected abstract int getSensorType();

  /**
   * Sets this Sensor Recorder listener.
   * @param listener
   */
  protected abstract void setListener(AbstractSensorListener listener);

}
